import bean.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import utils.MyBatisUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author 飞哥
 * @version V1.0
 * @package PACKAGE_NAME
 * @date 2021/7/10 10:11
 */
public class mybatisTest01 {

    @Test
    public void insertStudent() throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(is);
        /**
         * openSession(false); 手动提交事务
         * openSession(true);  自动提交事务
         * openSession();  默认是openSession(false);手动提交事务
         */
        SqlSession sqlSession = factory.openSession();

        String sqlId = "dao.StudentDao.insertStudent";
        Student student = new Student(1003, "张飒", "zhangsa@163.com", 19);
        int insert = sqlSession.insert(sqlId, student);

        //记得提交事务
        sqlSession.commit();
        //记得关闭sqlSession对象
        sqlSession.close();

        System.out.println("执行insetStudent方法插入了" + insert + "行数据");
    }

    @Test
    public void selectStudents() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();//工具类中是手动提交事务
        List<Student> list = sqlSession.selectList("dao.StudentDao.queryStudents");
        for (Student student : list) {
            System.out.println("学生信息：" + student);
        }

        //记得关闭sqlSession对象
        sqlSession.close();
    }

    @Test
    public void updateStudent() throws IOException {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(Resources.getResourceAsStream("mybatis.xml"));
        SqlSession sqlSession = factory.openSession(true);//自动提交事务
        String sqlId = "dao.StudentDao.updateStudent";
        Student student = new Student();
        student.setId(1003);
        student.setName("代心如");
        student.setEmail("daidai@163.com");
        student.setAge(21);
        int update = sqlSession.update(sqlId, student);

        //关闭sqlSession对象
        sqlSession.close();

        System.out.println("调用updateStudent方法修改了" + update + "行");
    }
}
